package com.jiepos.mpos.core.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;

import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.util.DateUtil;
/**
 * 
 * <p>标题: —— 父类控制器</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @author 娄伟峰
 * @version 1.0
 * @since 2017年4月10日 下午3:27:42
 * @history（历次修订内容、修订人、修订时间等）
 */
@Controller
public class BaseController {
	/** 自己的日志 */
	private final Logger currLog = LoggerFactory.getLogger(BaseController.class);

	/** 子类的日志 */
	public final Logger log = LoggerFactory.getLogger(getClass());

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Integer.class, null, new CustomNumberEditor(Integer.class, null, true));
		binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, null, true));
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
		binder.registerCustomEditor(Float.class, null, new CustomNumberEditor(Float.class, null, true));
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
	}

	/**
	 * 获取分页数据，并拼装按钮和菜单权限,供子类调用
	 * 
	 * @param request
	 * @param response
	 * @param pagination
	 * @return
	 */
	public ModelAndView getPaginationList(HttpServletRequest request, HttpServletResponse response, ModelAndView model,
			Pagination pagination) {
		String menuCode = request.getParameter("menuCode");
		Map map = new HashMap();
		map.put("menuCode", menuCode);
		map.put("pagination", pagination);
		map.putAll(getDateTime());
		model.addAllObjects(map);
		return model;
	}

	/**
	 * 打开详细页面时权限控制
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	public ModelAndView getDetail(HttpServletRequest request, HttpServletResponse response, ModelAndView model) {
		String menuCode = request.getParameter("menuCode");
		String pageType = request.getParameter("pageType");
		Map map = new HashMap();
		String authButton = null;// loginService.getButtonOperateByMenuCode(
		// request, menuCode);
		List<Map> allButtonList = null;// loginService.getAllButtonByMenuCode(
		// menuCode);
		map.put("authButton", authButton);
		map.put("allButtonList", allButtonList);
		map.put("menuCode", menuCode);
		map.put("pageType", pageType);
		map.putAll(getDateTime());
		model.addAllObjects(map);
		return model;
	}

	/***
	 * 获取登录session
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public Map getLoginUser(HttpServletRequest request, HttpServletResponse response) {
		String loginUser = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_USER));
		Map map = new HashMap();
		map.put(SystemConstant.SESSION_LOGIN_USER, loginUser);
		map.put("request", request);
		String menuCode = request.getParameter("menuCode");
		map.put("menuCode", menuCode);
		
		
		String ins_uuid = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_INS_UUID));
		map.put(SystemConstant.SESSION_LOGIN_INS_UUID, ins_uuid);
		return map;
	}

	/**
	 * 清空cookie
	 * 
	 * @param request
	 * @param response
	 */
	public void clearCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		try {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals("fileDownload")) {
					Cookie cookie = new Cookie(cookies[i].getName(), null);
					cookie.setMaxAge(0);
					cookie.setPath("/");// 根据你创建cookie的路径进行填写
					response.addCookie(cookie);
				}

			}
		} catch (Exception ex) {
			log.error("清空Cookies发生异常！");
		}
	}

	/**
	 * 设置下载参数
	 * 
	 * @param request
	 * @param response
	 * @param fileName
	 */
	public void setFileParam(HttpServletRequest request, HttpServletResponse response, String fileName) {
		OutputStream os = null;
		File file = null;
		try {
			String newName = null;
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
				newName = URLEncoder.encode(fileName, "UTF-8");  
			} else {  
				newName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");  
			}
			response.setHeader("Content-Disposition", "attachment;fileName=" + newName);
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setStatus(200);
			Cookie cookie = new Cookie("fileDownload", "true");
			cookie.setPath("/");
			response.addCookie(cookie);
			file = new File(fileName);
			os = response.getOutputStream();
			os.write(FileUtils.readFileToByteArray(file));
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if(file != null){
					file.delete();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 设置下载参数
	 * 
	 * @param request
	 * @param response
	 * @param fileName
	 */
	public void setFileParam(HttpServletRequest request, HttpServletResponse response, String fileName,String filePath) {
	 
		response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
		response.setContentType("application/octet-stream; charset=utf-8");
		response.setStatus(200);
		Cookie cookie = new Cookie("fileDownload", "true");
		cookie.setPath("/");
		response.addCookie(cookie);
		File file = new File(filePath);
		OutputStream os = null;
		;
		try {
			os = response.getOutputStream();
			os.write(FileUtils.readFileToByteArray(file));
			os.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 设置下载参数
	 * 
	 * @param request
	 * @param response
	 * @param fileName
	 */
	public void setErrorFileParam(HttpServletRequest request, HttpServletResponse response, String msg) {
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setStatus(500);
		try {
			response.getWriter().print(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Map<String, String> getDateTime(){
		Map<String, String> date = new HashMap<>();
		date.put("currentDate", DateUtil.getCurrDate());
		date.put("currentTime", DateUtil.getCurrTime());
		date.put("yestedayDate", DateUtil.getPreDate());
		date.put("lastMonth", DateUtil.getLastMonth(DateUtil.FORMAT_DATE_1));
		date.put("nowDate", DateUtil.getNowDateTime());
		return date;
	}
}
